import needle, { NeedleResponse } from "needle";
enum methods {
  get = "get",
  post = "post",
}
interface optionsProp {
  method?: methods;
  headers?: any;
  data?: any;
  url: string;
}
interface MyResponse {
  success: boolean;
  data?: any;
  msg?: string;
  code?: number;
}
const request = async (options: optionsProp): Promise<MyResponse> => {
  options.method = options.method || methods.get;
  return new Promise((resolve) => {
    const callBack = (
      error: Error | null,
      response: NeedleResponse,
      body: any
    ) => {
      if (error) {
        resolve({
          success: false,
          code: 500,
          msg: "服务器出问题了",
        });
      }
      if (!response || response.statusCode !== 200) {
        resolve({
          success: false,
          code: 500,
        });
      } else {
        resolve({
          success: true,
          data: response.body,
        });
      }
    };
    switch (options.method) {
      case methods.get:
        needle.get(options.url, callBack);
        break;
      case methods.post:
        if (options.data) {
          options.data = JSON.stringify(options.data);
        }
        const realOptions = {
          headers: {
            "content-type": "application/json",
            accept: "application/json",
          },
        };
        needle.post(options.url, options.data, realOptions, callBack);
        break;
      default:
        break;
    }
  });
};

export default request;
